package com.xyx.uniplugin_bloodoxygen.device;

import com.xyx.uniplugin_bloodoxygen.datastructs.FXFrameData;
import com.xyx.xyxandwxx_ble.async.IAction;
import com.xyx.xyxandwxx_ble.interfaces.IDevice;

import java.util.ArrayList;
import java.util.List;

public class NormalDevice {
    private static final String TAG = "NormalDevice";

    public static byte[] headers = new byte[]{ (byte)0xAA, 0x00, 0x00, 0x55, (byte)0xF0, (byte)0xC0};
    /**
     * 设备
     */
    public IDevice device;
    /**
     * 缓存
     */
    private List<Byte> caches = new ArrayList<>();
    /**
     * 数据回调
     */
    private IAction.ActionOne<FXFrameData> callBack;

    public NormalDevice(IDevice device) {
        this.device = device;
        this.device.setOnReceiveMessage(this::onMessageReceive);
    }

    /**
     * 设置回调
     * @param callBack 回调函数
     */
    public void setCallBack(IAction.ActionOne<FXFrameData> callBack){
        this.callBack = callBack;
    }

    protected void onMessageReceive(byte[] buffer) {
        for(int i = 0; i < buffer.length; i ++){
            caches.add(buffer[i]);
        }

        boolean isOk = true;
        for (int i = 0; i < headers.length; i ++) {
            if(caches.get(i) != headers[i]){
                isOk = false;
            }
        }

        if(!isOk) {
            caches.remove(0);
            return;
        }

        FXFrameData frameData = new FXFrameData();
        int startIndex = headers.length;
        frameData.address = caches.get(startIndex++);
        frameData.scale = caches.get(startIndex++);
        frameData.battery = caches.get(startIndex++);
        startIndex++;
        frameData.dataLen = caches.get(startIndex++);
        int totalSize = startIndex + frameData.dataLen + 1;
        if(caches.size() <= totalSize) {
            return;
        }

        List<Byte> res = caches.subList(startIndex, startIndex + frameData.dataLen);
        for(Byte b : res){
            frameData.buffer.add((int)b);
        }

        while (totalSize-- > 0) {
            caches.remove(0);
        }

        if(callBack != null) {
            try {
                callBack.action(frameData);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 连接设备
     * @param serverId 服务id
     * @param writeId 写入服务id
     * @param readId 读取服务id
     * @return 是否连接成功
     */
    public void connect(String serverId, String writeId, String readId, IAction.ActionOne<Boolean> callback) throws Exception {
        try {
            device.connect(serverId, writeId, readId).setTaskResultRun(callback);
        } catch (Exception e) {
            e.printStackTrace();
            callback.action(false);
        }
    }

}
